<template>
    <product-selection v-model="selectionVisible"
                       :product="product"
                       :initial-variant="variant"
                       ok-visible
                       :stepper-visible="false"
                       @ok="handleOk"/>
</template>

<script>
  import * as _ from "lodash"
  import { cart, catalog, security } from "@mall/api-services"
  import ProductSelection from "../../components/product/ProductSelection"
  import { Toast } from "vant"

  function findVariant(variants, variantId) {
    return _.find(variants, variant => variant.id === variantId)
  }

  export default {
    name: "CartItemSelection",
    components: { ProductSelection },
    model: {
      prop: "visible",
      event: "change-visible",
    },
    props: {
      visible: Boolean,
      item: cart.CartItem,
    },
    data() {
      return {
        selectionVisible: false,
        product: new catalog.Product(),
        variant: new catalog.ProductVariant(),
      }
    },
    watch: {
      visible: function(visible, oldVisible) {
        if (visible !== oldVisible) {
          this.selectionVisible = visible
        }
      },
      item(newItem, oldItem) {
        const { visible } = this
        if (newItem !== oldItem && visible) {
          this.refreshProduct()
        }
      },
      selectionVisible: function(visible, oldVisible) {
        if (visible !== oldVisible) {
          this.$emit("change-visible", visible)
        }
      },
    },
    methods: {
      handleOk(item) {
        const { item: cartItem, variantId } = this
        if (item.variantId === variantId) {
          this.$emit("change-visible", false)
          return
        }
        const customerId = security.SecurityUserHolder.getUserId()
        const updateCartItem = new cart.CartItem()
        updateCartItem.id = cartItem.id
        updateCartItem.productId = item.productId
        updateCartItem.variantId = item.variantId
        if (variantId !== cartItem.variantId) {
          updateCartItem.quantity = cartItem.quantity
        }
        Toast.loading()
        cart.CartServiceV1.updateCartItem(customerId, updateCartItem)
          .then(() => {
            this.$emit("change-visible", false)
            this.$emit("ok")
          })
          .finally(() => Toast.clear())
      },
      refreshProduct() {
        const { item, product } = this
        if (_.isEmpty(item)) {
          return
        }
        const { productId, variantId } = item
        if (_.isUndefined(product) || product.id !== productId) {
          Toast.loading()
          catalog.ProductServiceV1.getProduct(productId)
            .then(product => {
              this.product = product
              const variant = findVariant(product.variants, variantId)
              if (variant) {
                this.variant = variant
              }
            })
            .finally(() => Toast.clear())
        }
      },
    },
  }
</script>

<style scoped>

</style>
